package net.lgpage.http;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Map.Entry;

import net.lgpage.tool.GsonTool;
import net.lgpage.tool.TagTool;
import net.lgpage.util.Checker.StringUtils;
import net.lgpage.util.CustomMultipartEntity;
import net.lgpage.util.CustomMultipartEntity.ProgressListener;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.util.Log;

import com.matriq.cloudmanager.MyApp;

public class HttpConnectionUtil {

	private static String TAG = "HttpConnectionUtil";
	
	//public static String URL = "http://172.16.42.103:10001/CloudManager/";
	//public static String URL = "http://172.16.40.29:10001/CloudManager/";
	public static String URL = "http://172.16.40.30:10002/CloudManager/";
	public static int ConnectionTimeout = 5000;
	public static int SoTimeout = 21000;
	private static String sessionId = null;

	public static String requestObj(String url, String method, Object obj)
			throws Exception {
		String json = GsonTool.getGson().toJson(obj);
		return requestUrl(url, method, json, "application/json");
	}

	public static String requestMap(String url, String method,
			Map<String, String> map) throws Exception {
		StringBuffer sb = new StringBuffer();
		if(map!=null){
			for (Entry<String, String> e : map.entrySet()) {
				if(!StringUtils.isEmpty(e.getValue())){
					sb.append("&");
					sb.append(e.getKey());
					sb.append("=");
					sb.append(URLEncoder.encode(e.getValue(), "UTF-8"));
				}
			}
		}
		String params = sb.length()<=0?null:sb.substring(1);
		return requestUrl(url, method, params,
				"application/x-www-form-urlencoded");
	}

	public static String requestUrl(String url, String method, String content,
			String contentType) throws Exception {
		if("GET".equals(method)){
			if(content!=null){
				StringBuffer sb = new StringBuffer();
				sb.append(url);
				int at = url.indexOf("?");
				if(at>0){
					if(at<url.length()-1){
						sb.append("&");
						sb.append(content);
					}else if(at == url.length()-1){
						sb.append(content);
					}
				}else{
					sb.append("?");
					sb.append(content);
				}
				url = sb.toString();
			}
		}
		URL addr_url = new URL(url);
		TagTool.v(TAG, url);
		HttpURLConnection conn = (HttpURLConnection) addr_url.openConnection();
		conn.setRequestMethod(method);
		conn.setConnectTimeout(ConnectionTimeout);
		conn.setReadTimeout(SoTimeout);
		conn.setUseCaches(false);
		conn.setRequestProperty("Content-type", contentType);
		if("GET".equals(method)){
			
		}else{
			conn.setDoOutput(true);
			conn.setDoInput(true);
			if (content != null) {
				PrintWriter pw = new PrintWriter(conn.getOutputStream());
				TagTool.v(TAG, "content:" + content);
				pw.write(content);
				pw.flush();
				pw.close();
			}
		}
		int responseCode = conn.getResponseCode();
		int contentLength = conn.getContentLength();
		if (responseCode == HttpURLConnection.HTTP_OK) {
			String strResult = null;
			InputStream is = conn.getInputStream();
			byte[] bs = getBytes(is);
			strResult = new String(bs);
			TagTool.v(TAG, strResult);
			return strResult;
		} else {
			TagTool.e(TAG, "错误状态码:" + responseCode);
			throw new Exception("错误状态码:" + responseCode);
		}
	}

	public static String requestAppendData(String appendurl, String method,
			String data) throws Exception {
		return requestUrl(URL + appendurl, method, data, "application/json");
	}

	public static String requestAppendObj(String appendurl, String method,
			Object obj) throws Exception {
		return requestObj(URL + appendurl, method, obj);
	}

	public static String requestAppendMap(String appendurl, String method,
			Map<String, String> map) throws Exception {
		TagTool.d(TAG, "put:" + map);
		return requestMap(URL + appendurl, method, map);
	}
	
	
	public static String postFiles(String url, Map<String, String> map,
			Map<String, File> filemap, ProgressListener listener) throws Exception{
		HttpPost post = new HttpPost(URL + url);
		TagTool.d(TAG, url);
		TagTool.d(TAG, "dataput:" + map);
		TagTool.d(TAG, "filedataput:" + filemap);
		DefaultHttpClient hc = new DefaultHttpClient();
		if (MyApp.getApp().getCookieStore() != null) {
			hc.setCookieStore(MyApp.getApp().getCookieStore());
		}
		HttpParams params = null;
		params = hc.getParams();
		post.setHeader("Charset", "UTF-8");
		HttpConnectionParams.setConnectionTimeout(params, ConnectionTimeout);
		//HttpConnectionParams.setSoTimeout(params, SoTimeout);
		CustomMultipartEntity entity = new CustomMultipartEntity(listener);
		if(filemap!=null)
		for (Entry<String, File> e : filemap.entrySet()) {
			if (e.getValue() != null && e.getValue().exists()) {
				entity.addPart(e.getKey(), new FileBody(e.getValue()));
			}
		}
		if(map!=null)
		for (Entry<String, String> e : map.entrySet()) {
			entity.addPart(e.getKey(),
					new StringBody(e.getValue(), Charset.forName("UTF-8")));
		}
		post.setEntity(entity);
		HttpResponse response = hc.execute(post);
		response.setHeader("Charset", "UTF-8");
		int stateCode = response.getStatusLine().getStatusCode();
		StringBuffer sb = new StringBuffer();
		if (stateCode == HttpStatus.SC_OK) {
			HttpEntity result = response.getEntity();
			if (result != null) {
				InputStream is = result.getContent();
				BufferedReader br = new BufferedReader(
						new InputStreamReader(is));
				String tempLine;
				while ((tempLine = br.readLine()) != null) {
					sb.append(tempLine);
				}
			}
		}
		post.abort();
		TagTool.d(TAG, sb.toString());
		return sb.toString();
	}

	public static byte[] getBytes(InputStream is) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		try {
			while ((len = is.read(buffer)) != -1) {
				bos.write(buffer, 0, len);
			}
			is.close();
			bos.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (is != null)
				try {
					is.close();
				} catch (IOException e) {
				}
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
				}
			}
		}
		byte[] result = bos.toByteArray();
		return result;
	}

}
